package com.mit.wx.controller;

import com.mit.wx.dto.AdminDto;
import com.mit.wx.service.AdminService;
import com.mit.wx.util.AccessAuthUtil;
import com.mit.wx.vo.BasicJsonResult;
import com.mit.wx.vo.WxLoginState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 2018/10/20 Create by 郭文梁
 * AdminController
 * 管理员访问控制器
 *
 * @author 郭文梁
 * @date 2018/10/20
 */
@RestController
@Slf4j
@RequestMapping("/admin-public")
public class AdminPublicController {
    private final AdminService adminService;

    @Autowired
    public AdminPublicController(AdminService adminService) {
        this.adminService = adminService;
    }

    @PostMapping("/login")
    public BasicJsonResult<AdminDto> login(HttpServletRequest request,
                                           HttpServletResponse response,
                                           String name, String password) {
        if (AccessAuthUtil.checkAuth(request)) {
            return BasicJsonResult.error(2, "请先注销");
        }
        AdminDto admin = adminService.login(name, password);
        if (admin == null) {
            return BasicJsonResult.error(1, "用户名或密码错误");
        }
        AccessAuthUtil.grant(request, response, admin);
        return BasicJsonResult.ok(admin);
    }

    @PostMapping("/logout")
    public BasicJsonResult<AdminDto> logout(HttpSession session) {
        session.invalidate();
        return BasicJsonResult.ok("success");
    }

    @GetMapping("/account")
    public BasicJsonResult<AdminDto> account(HttpServletRequest request) {
        boolean isLogin = AccessAuthUtil.checkAuth(request);
        if (isLogin) {
            AdminDto admin = (AdminDto) request.getSession().getAttribute(AdminDto.IN_SESSION_NAME);
            return BasicJsonResult.ok(admin);
        } else {
            return BasicJsonResult.error(1, "未登录");
        }
    }

    @GetMapping("/bind-open-id")
    public void bindOpenId(String state, String code, HttpServletResponse response) throws IOException {
        Integer adminId = getAdminIdFromState(state);
        AdminDto result = adminService.bindOpenIdByCode(adminId, code);
        if (result != null) {
            response.sendRedirect("/bind-open-id-success.html");
        } else {
            response.sendRedirect("/bind-open-id-fail.html");
        }
    }

    private Integer getAdminIdFromState(String state) {
        return WxLoginState.fromBase64(state).getAdminId();
    }
}
